import { Card, Form, Input, Modal, Spin } from 'antd';
import React, { useContext, useRef, useState } from 'react';
import { useBoolean } from 'ahooks';
import PubSub from 'pubsub-js';
import FlowContext from '@/pages/Flow/FlowContext';
import request from '@/utils/request';
import VersionPageTable from '../../VersionPageTable';
import useModal from '@/hooks/UseModal';
import ExclusiveGatewayEditor from '@/pages/ExclusiveGateway/ExclusiveGatewayEditor';

function ExclusivePanel({ form, node, update }) {
  const { getFieldDecorator, validateFields } = form;
  const { label: gatewayName, nodeCode: gatewayCode, nodeId: gatewayId, nodeVersionId } = node;

  // 全局Context
  const {
    state: { processId, versionId, readOnly },
  } = useContext(FlowContext);

  // 页面Loading
  const [loading, setLoading] = useState(false);

  // 编辑状态控制
  const isEdit = !!gatewayId;
  const [editDisabled, { setFalse: enableEdit, setTrue: disableEdit }] = useBoolean(isEdit);

  // 弹窗配置
  const { visible, data, showModal, hideModal } = useModal();

  // 保存表单
  function save() {
    validateFields((err, data) => {
      if (err) {
        return;
      }

      setLoading(true);
      if (isEdit) {
        request
          .post(`/exclusiveGateway/updateExclusiveGateway`, { data })
          .then(() => {
            update({
              label: data.gatewayName,
              nodeCode: data.gatewayCode,
            });
            disableEdit();
            PubSub.publish(`nodeSave_${processId}_${versionId}`);
          })
          .finally(() => {
            setLoading(false);
          });
      } else {
        request
          .post(`/exclusiveGateway/createExclusiveGateway`, { data })
          .then(({ gatewayId }) => {
            update({
              nodeId: gatewayId,
              label: data.gatewayName,
              nodeCode: data.gatewayCode,
            });
            disableEdit();
            PubSub.publish(`nodeSave_${processId}_${versionId}`);
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  }

  function renderExtra() {
    if (readOnly) {
      return null;
    }
    return editDisabled ? <a onClick={enableEdit}>编辑</a> : <a onClick={save}>保存</a>;
  }

  function renderForm() {
    return (
      <Form>
        <Form.Item>
          {getFieldDecorator('gatewayId', {
            initialValue: gatewayId,
          })(<Input hidden />)}
        </Form.Item>
        <Form.Item label="网关名称">
          {getFieldDecorator('gatewayName', {
            initialValue: gatewayName,
            rules: [
              {
                required: true,
                message: '网关名称不能为空',
              },
            ],
          })(<Input disabled={editDisabled} placeholder="请输入" />)}
        </Form.Item>
        <Form.Item label="网关编码">
          {getFieldDecorator('gatewayCode', {
            initialValue: gatewayCode,
            rules: [
              {
                required: true,
                message: '网关编码不能为空',
              },
            ],
          })(<Input disabled={editDisabled} placeholder="请输入" />)}
        </Form.Item>
      </Form>
    );
  }

  const versionTableRef = useRef();

  function renderVersionList() {
    if (!isEdit) {
      return null;
    }
    return (
      <VersionPageTable
        ref={versionTableRef}
        style={{ marginTop: '16px' }}
        element="exclusiveGateway"
        elementIdKey="gatewayId"
        elementId={gatewayId}
        elementVersionId={nodeVersionId}
        onClickConfig={({ elementId, versionId, readOnly }) => {
          showModal({ gatewayId: elementId, versionId, readOnly });
        }}
        readOnly={readOnly}
        onValidVersion={nodeVersionId => {
          update({ nodeVersionId });
          PubSub.publish(`nodeSave_${processId}_${versionId}`);
        }}
      />
    );
  }

  return (
    <Card type="inner" size="small" title="互斥网关" bordered={false} extra={renderExtra()}>
      <Spin spinning={loading}>
        {renderForm()}
        {renderVersionList()}
      </Spin>
      <Modal
        width={1000}
        title="互斥网关"
        visible={visible}
        onCancel={hideModal}
        destroyOnClose
        footer={null}
      >
        <ExclusiveGatewayEditor
          {...data}
          onCancel={hideModal}
          onSaveAndValidVersion={() => {
            versionTableRef.current && versionTableRef.current.setCurrentVersionId(data.versionId);
            update({ nodeVersionId: data.versionId });
            PubSub.publish(`nodeSave_${processId}_${versionId}`);
            versionTableRef.current && versionTableRef.current.refresh();
          }}
        />
      </Modal>
    </Card>
  );
}

export default Form.create()(ExclusivePanel);
